﻿using MediatR;
using Messhall.Domain.Permission.DomainServices;
using Messhall.Domain.Permission.IRepositorys;
using Messhall.Framework.Autofac;

namespace Messhall.Application.Permission.Commands.Permission;

/// <summary>
/// 创建菜单Handler
/// </summary>
public class CreatePermissionCommandHandler : CommandHandlerBase, IRequestHandler<CreatePermissionCommand, bool>
{
    private PermissionDomainService _permissionDoaminService;

    public CreatePermissionCommandHandler(PermissionDomainService permissionDoaminService)
    {
        this._permissionDoaminService = permissionDoaminService;
    }

    public async Task<bool> Handle(CreatePermissionCommand createPermissionCommand, CancellationToken cancellationToken)
    {
        var request = createPermissionCommand.Request ?? throw new ArgumentNullException("request is null");
        
        if (string.IsNullOrWhiteSpace(request.Code))
        {
            request.Code = await _permissionDoaminService.GetCode();
        }

        if (string.IsNullOrWhiteSpace(request.Name))
        {
            throw new Exception("name is null");
        }

        var permission = new Domain.Permission.BusinessObjects.Permission(request.ParentId, request.Icon, request.Name,
            request.Code,
            request.Uri, request.Remark);

        foreach (var item in request.Authority)
        {
            permission.SetAuthority(item.Name, item.Code);
        }

        await base.permissionRepository.AddAsync(permission);
        await base.appUnitOfWork.SaveChangesAsync(cancellationToken);

        return true;
    }
}